package com.example.healkep;

import static com.example.healkep.LoginActivity.setId;
import static com.example.healkep.LoginActivity.setSessionID;
import static com.example.healkep.LoginActivity.setUser;

import androidx.appcompat.app.AppCompatActivity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.widget.Button;
import android.widget.Toast;

import com.example.healkep.MainActivity.MainActivity;
import com.example.healkep.utils.Captcha.Captcha;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Objects;
import java.util.Random;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class CaptchaLActivity extends AppCompatActivity {

    public static boolean result;
    private Captcha captcha;

    public boolean isResult() {
        return result;
    }

    public void setResult(boolean result) {
        this.result = result;
    }

    @SuppressLint("UseCompatLoadingForDrawables")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_captchal);
        captcha = findViewById(R.id.captCha);
        Button btnMode = findViewById(R.id.btn_mode);
        Button refresh = findViewById(R.id.refreshl);

        final Bundle bundle = getIntent().getExtras();
        String json = bundle.getString("json");
        String username = bundle.getString("username");

        btnMode.setOnClickListener(v -> {
            if (captcha.getMode() == Captcha.MODE_BAR) {
                captcha.setMode(Captcha.MODE_NONBAR);
                btnMode.setText("滑动条模式");
            } else {
                captcha.setMode(Captcha.MODE_BAR);
                btnMode.setText("无滑动条模式");
            }
        });

        refresh.setOnClickListener(v -> {
            Random r = new Random();
            int id = r.nextInt(7) + 1;
            switch (id){
                case 1:captcha.setBitmap(R.drawable.captcha1);break;
                case 2:captcha.setBitmap(R.drawable.captcha2);break;
                case 3:captcha.setBitmap(R.drawable.captcha3);break;
                case 4:captcha.setBitmap(R.drawable.captcha4);break;
                case 5:captcha.setBitmap(R.drawable.captcha5);break;
                case 6:captcha.setBitmap(R.drawable.captcha6);break;
                case 7:captcha.setBitmap(R.drawable.captcha7);break;
                default:break;
            }
        });

        captcha.setCaptchaListener(new Captcha.CaptchaListener() {
            @Override
            public String onAccess(long time) {
               new Thread(() -> {
                    try {
                        OkHttpClient client = new OkHttpClient();
                        Request request = new Request.Builder()
                                .url(LoginActivity.url + "/login/login")
                                .post(RequestBody.create(MediaType.parse("application/json"), json))
                                .build();
                        Response response = client.newCall(request).execute();//header不要改,body(x)其中x是返回Controller的return,
                        String responseData = Objects.requireNonNull(response.body()).string();
                        JSONObject jsonobject = new JSONObject(responseData);
                        String result = jsonobject.getString("register");
                        if (!result.equals("false")) {
                            runOnUiThread(() -> {
                                try {
                                    setSessionID(jsonobject.getString("sessionID"));
                                } catch (JSONException e) {
                                    setSessionID(null);
                                }
                                try {
                                    Object temp1 = jsonobject.getJSONObject("login");
                                    JSONObject temp2 = new JSONObject(temp1.toString());
                                    setUser(temp2.getString("username"));
                                    setId(temp2.getInt("id"));
                                } catch (JSONException ignored) {
                                    setUser(null);
                                }
                                setUser(username);
                                Intent intent = new Intent();
                                Toast.makeText(CaptchaLActivity.this, "登录成功:" + username, Toast.LENGTH_SHORT).show();
                                intent.setClass(CaptchaLActivity.this, MainActivity.class);
                                startActivity(intent);
                            });
                        } else {
                            Intent intent = new Intent(CaptchaLActivity.this, LoginActivity.class);
                            runOnUiThread(() -> Toast.makeText(CaptchaLActivity.this, "登录失败", Toast.LENGTH_SHORT).show());
                            startActivity(intent);
                        }

                    } catch (Exception e) {
                        Intent intent = new Intent(CaptchaLActivity.this, LoginActivity.class);
                        runOnUiThread(() -> Toast.makeText(CaptchaLActivity.this, "连接失败", Toast.LENGTH_SHORT).show());
                        startActivity(intent);
                    }
                }).start();
                return "验证通过";
            }

            @Override
            public String onFailed(int count) {
                Toast.makeText(CaptchaLActivity.this, "验证失败,失败次数" + count, Toast.LENGTH_SHORT).show();
                return "验证失败";
            }

            @Override
            public String onMaxFailed() {
                Intent intent = new Intent(CaptchaLActivity.this, LoginActivity.class);
                Toast.makeText(CaptchaLActivity.this, "验证超过次数，重新登陆", Toast.LENGTH_SHORT).show();
                startActivity(intent);
                return "重新登录";
            }
        });
    }

    public Bitmap getfrombyte(byte[] bytes) {
        if (bytes != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
            return bitmap;
        } else {
            return null;
        }
    }
}